package com.company;

import java.io.*;
import java.net.Socket;
import java.net.URLConnection;
import java.nio.file.Files;
import java.util.Date;

/**
 * Created by Henry on 2018/4/22.
 */
public class RequestHandle implements Runnable {
    private Socket connection;
    private String indexFileName = "index.html";
    private File rootFile;

    public RequestHandle(Socket socket) {
        this.connection = socket;
    }
    @Override
    public void run() {
        try {
            OutputStream out = new BufferedOutputStream(connection.getOutputStream());
            Writer writer = new OutputStreamWriter(out);
            Reader in = new InputStreamReader(new BufferedInputStream(connection.getInputStream()));
            StringBuilder requestLine = new StringBuilder();
            while(true) {
                int c = in.read();
                if(c == '\r' || c == '\n' || c == -1) break;
                requestLine.append((char) c);
            }
            System.out.println(requestLine);
            String get = requestLine.toString();
            String[] tokens = get.split("\\s+");
            String method = tokens[0];
            String version = null;
            if(method.equals("GET")){
                String fileName = tokens[1];
                if (fileName.endsWith("/")) {fileName += indexFileName;}
                String contentType = URLConnection.getFileNameMap().getContentTypeFor(fileName);
                if (tokens.length > 2) {version = tokens[2];}
                File file = new File("C:\\java\\HttpServer\\src\\"+ fileName.substring(1, fileName.length()));
                if (file.canRead()) {
                    byte[] theData = Files.readAllBytes(file.toPath());
                    if (version.startsWith("HTTP/")) {
                        sendHeader(writer, "HTTP/1.0 200 OK", contentType, theData.length);
                    }
                    out.write(theData);
                    out.flush();
                } else { // 无法找到文件
                    String body = new StringBuilder("<HTML>\r\n")
                            .append("<HEAD><TITLE>File Not Found</TITLE>\r\n")
                            .append("<HEAD>\r\n")
                            .append("<BODY>")
                            .append("<H1>HTTP Error 404 :File Not Found</H1>\r\n")
                            .append("</BODY></HTML>\r\n")
                            .toString();
                    if(version.startsWith("HTTP/")) {
                        sendHeader(writer, "HTTP/1.0 404 File Not Found", "text/html, charset=utf-8", body.length());
                    }
                    writer.write(body);
                    writer.flush();
                }





            }else {

            }

        }catch(IOException e ){

        }
    }

    private void sendHeader(Writer out, String responseCode, String contentType, int length) throws IOException{
        out.write(responseCode + "\r\n");
        Date now = new Date();
        out.write("Date: " + now + "\r\n");
        out.write("Server :HttpServer 1.0\r\n");
        out.write("Content-length: " + length + "\r\n");
        out.write("Content-type: " + contentType + "\r\n\r\n");
        out.flush();
    }
}
